package com.zhentao.device.Controller;

import com.zhentao.device.service.AlertService;
import com.zhentao.device.service.WaterQualityAnomalyService;
import com.zhentao.device.websocket.AlertWebSocketHandler;
import com.zhentao.device.mapper.WaterQualityAnomalyMapper;
import com.zhentao.equipment.mapper.DeviceInfoMapper;
import com.zhentao.pojo.WaterQualityAnomaly;
import com.zhentao.pojo.DeviceInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.util.Enum.ApiServiceExceptionEnum;
import com.zhentao.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 告警控制器
 * 提供告警相关的REST API接口
 */
@RestController
@RequestMapping("/Alert")
@CrossOrigin(origins = "*")
public class AlertController {

    @Autowired
    private AlertService alertService;

    @Autowired
    private WaterQualityAnomalyService waterQualityAnomalyService;

    @Autowired
    private WaterQualityAnomalyMapper waterQualityAnomalyMapper;

    @Autowired
    private DeviceInfoMapper deviceInfoMapper;

    @Autowired
    private com.zhentao.device.mapper.WaterAnomalyLogMapper waterAnomalyLogMapper;

    /**
     * 获取告警列表（支持分页）
     */
    @GetMapping("/list")
    public ResultVo getAlertList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String status) {

        try {
            System.out.println("📡 获取告警列表 - 页码: " + page + ", 每页: " + pageSize + ", 状态: " + status);

            // 创建分页对象
            Page<WaterQualityAnomaly> pageObj = new Page<>(page, pageSize);

            // 创建查询条件
            QueryWrapper<WaterQualityAnomaly> queryWrapper = new QueryWrapper<>();
            if (status != null && !status.isEmpty()) {
                // 将字符串状态转换为数字状态
                Integer statusCode = convertStatusToCode(status);
                if (statusCode != null) {
                    queryWrapper.eq("handle_status", statusCode);
                    System.out.println("🔍 状态筛选: " + status + " -> " + statusCode);
                }
            }
            queryWrapper.orderByDesc("create_time");

            // 执行分页查询
            Page<WaterQualityAnomaly> resultPage = waterQualityAnomalyMapper.selectPage(pageObj, queryWrapper);

            // 构建返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("data", resultPage.getRecords());
            result.put("total", resultPage.getTotal());
            result.put("page", page);
            result.put("pageSize", pageSize);
            result.put("totalPages", resultPage.getPages());
            result.put("hasNext", resultPage.hasNext());
            result.put("hasPrevious", resultPage.hasPrevious());

            System.out.println("✅ 分页查询完成 - 总数: " + resultPage.getTotal() +
                             ", 当前页: " + page + "/" + resultPage.getPages() +
                             ", 当前页数据量: " + resultPage.getRecords().size());

            return ResultVo.success(result);

        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error(500, "获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取告警详情
     */
    @GetMapping("/detail/{alertId}")
    public Map<String, Object> getAlertDetail(@PathVariable String alertId) {
        Map<String, Object> result = new HashMap<>();

        try {
            System.out.println("🔍 开始查询告警详情，ID: " + alertId);

            // 先检查数据库中是否有告警数据
            List<WaterQualityAnomaly> allAlerts = waterQualityAnomalyMapper.selectList(null);
            System.out.println("📊 数据库中总告警数量: " + allAlerts.size());

            if (!allAlerts.isEmpty()) {
                System.out.println("📋 数据库中的告警ID列表:");
                for (WaterQualityAnomaly alert : allAlerts) {
                    System.out.println("  - ID: " + alert.getAnomalyId() + ", 指标: " + alert.getIndicatorCode());
                }
            }

            // 尝试直接查询
            Long alertIdLong = Long.valueOf(alertId);
            WaterQualityAnomaly anomaly = waterQualityAnomalyMapper.selectById(alertIdLong);

            if (anomaly != null) {
                // 构建返回数据
                Map<String, Object> alertData = new HashMap<>();
                alertData.put("alertId", anomaly.getAnomalyId().toString());
                alertData.put("title", anomaly.getIndicatorCode() + "异常");
                alertData.put("description", anomaly.getIndicatorCode() + "值 " + anomaly.getCurrentValue() + " 超出正常范围 " + anomaly.getNormalRange());
                alertData.put("device", "监测点" + anomaly.getDeviceId());
                alertData.put("deviceId", anomaly.getDeviceId().toString());
                alertData.put("indicatorCode", anomaly.getIndicatorCode());
                alertData.put("currentValue", anomaly.getCurrentValue());
                alertData.put("normalRange", anomaly.getNormalRange());

                System.out.println("🔍 后端数据检查 - indicatorCode: " + anomaly.getIndicatorCode() +
                                 ", currentValue: " + anomaly.getCurrentValue() +
                                 ", normalRange: " + anomaly.getNormalRange());
                alertData.put("severity", anomaly.getSeverity());
                alertData.put("status", anomaly.getHandleStatus());
                alertData.put("createTime", anomaly.getCreateTime().toString());
                alertData.put("handlerId", "system");
                alertData.put("handleTime", null);

                // 获取相关设备数据（包含当前告警设备）
                List<Map<String, Object>> relatedDevices = getRelatedDevices(anomaly.getDeviceId());
                alertData.put("relatedDevices", relatedDevices);

                result.put("code", 200);
                result.put("msg", "获取成功");
                result.put("data", alertData);

                System.out.println("✅ 获取告警详情成功: " + alertId);
            } else {
                result.put("code", 404);
                result.put("msg", "告警不存在，请检查ID是否正确");
                result.put("data", null);
                System.out.println("❌ 告警不存在: " + alertId);
            }

        } catch (NumberFormatException e) {
            result.put("code", 400);
            result.put("msg", "告警ID格式错误: " + alertId);
            result.put("data", null);
            System.out.println("❌ 告警ID格式错误: " + alertId);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "获取失败: " + e.getMessage());
            result.put("data", null);
            System.out.println("❌ 获取告警详情失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 添加告警
     */
    @PostMapping("/add")
    public ResultVo addAlert(@RequestBody Map<String, Object> alertData) {
        try {
            String indicator = (String) alertData.get("indicator");
            Double currentValue = Double.valueOf(alertData.get("currentValue").toString());
            String normalRange = (String) alertData.get("normalRange");
            String deviceId = alertData.get("deviceId").toString();
            String deviceName = (String) alertData.getOrDefault("deviceName", deviceId);

            // 生成告警
            waterQualityAnomalyService.generateAlert(indicator, currentValue, normalRange, deviceId, deviceName, 0L);

            // 获取最新生成的告警并推送
            List<WaterQualityAnomaly> latestAlerts = waterQualityAnomalyService.getAlertsByDeviceId(deviceId);
            if (!latestAlerts.isEmpty()) {
                WaterQualityAnomaly latestAlert = latestAlerts.get(0);
                // 实时推送新告警
                AlertWebSocketHandler.broadcastNewAlert(latestAlert);
                System.out.println("📡 已推送新告警: " + latestAlert.getIndicatorCode() + "异常");
            }

            return ResultVo.success("添加成功");

        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error(500, "添加失败: " + e.getMessage());
        }
    }

    /**
     * 更新告警状态
     */
    @PutMapping("/status/{alertId}")
    public ResultVo updateAlertStatus(
            @PathVariable String alertId,
            @RequestBody Map<String, Object> statusData) {

        try {
            Long alertIdLong = Long.valueOf(alertId);
            Integer status = Integer.valueOf(statusData.get("status").toString());
            String handlerId = (String) statusData.getOrDefault("handlerId", "system");

            // 直接使用mapper更新状态
            int updated = waterQualityAnomalyMapper.updateStatus(alertIdLong, status, handlerId);
            boolean success = updated > 0;

            if (success) {
                // 实时推送告警状态更新
                AlertWebSocketHandler.broadcastAlertUpdate(alertIdLong, status, handlerId);
                System.out.println("📡 已推送告警状态更新: " + alertId + " -> " + status);

                return ResultVo.success("更新成功");
            } else {
                return ResultVo.error(404, "告警不存在");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error(500, "更新失败: " + e.getMessage());
        }
    }

    /**
     * 批量处理告警
     */
    @PostMapping("/batch-handle")
    public ResultVo batchHandleAlerts(@RequestBody Map<String, Object> batchData) {
        try {
            @SuppressWarnings("unchecked")
            List<String> alertIdStrings = (List<String>) batchData.get("alertIds");
            String handlerId = (String) batchData.getOrDefault("handlerId", "system");
            Integer status = Integer.valueOf(batchData.get("status").toString());

            // 转换字符串ID为Long类型
            List<Long> alertIds = alertIdStrings.stream()
                    .map(Long::valueOf)
                    .collect(java.util.stream.Collectors.toList());

            // 直接使用mapper批量更新状态
            int successCount = waterQualityAnomalyMapper.batchUpdateStatus(alertIds, status, handlerId);

            // 实时推送批量处理结果
            AlertWebSocketHandler.broadcastAlertUpdate(null, status, handlerId);
            System.out.println("📡 已推送批量处理结果: " + successCount + " 条告警");

            Map<String, Object> result = new HashMap<>();
            result.put("successCount", successCount);
            result.put("totalCount", alertIds.size());

            return ResultVo.success(ApiServiceExceptionEnum.valueOf("批量处理完成，成功处理 " + successCount + " 条告警"), result);

        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error(500, "批量处理失败: " + e.getMessage());
        }
    }

    /**
     * 将字符串状态转换为数字状态码
     */
    private Integer convertStatusToCode(String status) {
        if (status == null || status.isEmpty()) {
            return null;
        }

        switch (status.toLowerCase()) {
            case "unhandled":
                return 1; // 未处理
            case "confirmed":
                return 2; // 已确认
            case "handled":
                return 3; // 已处理
            case "all":
            default:
                return null; // 全部，不筛选
        }
    }

    /**
     * 获取WebSocket连接状态
     */
    @GetMapping("/ws/status")
    public Map<String, Object> getWebSocketStatus() {
        Map<String, Object> result = new HashMap<>();

        try {
            Map<String, Object> status = new HashMap<>();
            status.put("connectionCount", AlertWebSocketHandler.getConnectionCount());
            status.put("userCount", AlertWebSocketHandler.getUserCount());
            status.put("timestamp", System.currentTimeMillis());

            result.put("code", 200);
            result.put("msg", "获取成功");
            result.put("data", status);

        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "获取失败: " + e.getMessage());
            result.put("data", null);
        }

        return result;
    }

    /**
     * 手动触发告警推送（用于测试）
     */
    @PostMapping("/ws/test-push")
    public Map<String, Object> testPushAlert(@RequestBody Map<String, Object> testData) {
        Map<String, Object> result = new HashMap<>();

        try {
            String message = (String) testData.getOrDefault("message", "测试推送消息");
            String type = (String) testData.getOrDefault("type", "test");

            Map<String, Object> pushData = new HashMap<>();
            pushData.put("type", type);
            pushData.put("message", message);
            pushData.put("timestamp", System.currentTimeMillis());
            pushData.put("data", testData.get("data"));

            // 广播测试消息
            AlertWebSocketHandler.broadcastToAll(pushData);

            result.put("code", 200);
            result.put("msg", "推送成功");
            Map<String, Object> data = new HashMap<>();
            data.put("connections", AlertWebSocketHandler.getConnectionCount());
            result.put("data", data);

        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "推送失败: " + e.getMessage());
            result.put("data", null);
        }

        return result;
    }

    /**
     * 获取告警统计
     */
    @GetMapping("/stats")
    public ResultVo getAlertStats() {
        try {
            // 直接使用mapper获取统计信息
            Map<String, Object> result = waterQualityAnomalyMapper.selectAlertStats();
            Map<String, Integer> stats = new HashMap<>();

            // 转换结果类型
            if (result != null) {
                stats.put("total", result.get("total") != null ? ((Number) result.get("total")).intValue() : 0);
                stats.put("unhandled", result.get("unhandled") != null ? ((Number) result.get("unhandled")).intValue() : 0);
                stats.put("confirmed", result.get("confirmed") != null ? ((Number) result.get("confirmed")).intValue() : 0);
                stats.put("handled", result.get("handled") != null ? ((Number) result.get("handled")).intValue() : 0);
            } else {
                // 如果查询结果为空，返回默认值
                stats.put("total", 0);
                stats.put("unhandled", 0);
                stats.put("confirmed", 0);
                stats.put("handled", 0);
            }

            // 实时推送统计更新
            AlertWebSocketHandler.broadcastStatsUpdate(stats);
            System.out.println("📡 已推送告警统计更新: " + stats);

            return ResultVo.success(stats);

        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error(500, "获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取告警处理记录
     */
    @GetMapping("/process-records/{alertId}")
    public Map<String, Object> getProcessRecords(@PathVariable String alertId) {
        Map<String, Object> result = new HashMap<>();

        try {
            System.out.println("📋 获取告警处理记录，ID: " + alertId);

            Long alertIdLong = Long.valueOf(alertId);

            // 查询数据库中的真实处理记录
            List<Map<String, Object>> processRecords = getRealProcessRecords(alertIdLong);

            result.put("code", 200);
            result.put("msg", "获取成功");
            result.put("data", processRecords);

            System.out.println("✅ 获取处理记录成功，记录数: " + processRecords.size());

        } catch (NumberFormatException e) {
            result.put("code", 400);
            result.put("msg", "告警ID格式错误: " + alertId);
            result.put("data", null);
            System.out.println("❌ 告警ID格式错误: " + alertId);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "获取失败: " + e.getMessage());
            result.put("data", null);
            System.out.println("❌ 获取处理记录失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 添加处理记录（保存到数据库）
     */
    @PostMapping("/process-records/{alertId}")
    public Map<String, Object> addProcessRecord(
            @PathVariable String alertId,
            @RequestBody Map<String, Object> recordData) {
        Map<String, Object> result = new HashMap<>();

        try {
            System.out.println("📝 添加处理记录到数据库，告警ID: " + alertId);

            Long alertIdLong = Long.valueOf(alertId);
            Integer status = Integer.valueOf(recordData.get("status").toString());
            String description = (String) recordData.getOrDefault("description", "");

            // 创建处理记录实体并保存到数据库
            com.zhentao.pojo.WaterAnomalyLog log = new com.zhentao.pojo.WaterAnomalyLog();
            log.setAnomalyId(alertIdLong.intValue());
            log.setStatus(status);
            log.setCreateTime(new Date());

            int insertResult = waterAnomalyLogMapper.insert(log);
            boolean success = insertResult > 0;

            if (success) {
                result.put("code", 200);
                result.put("msg", "添加成功");
                Map<String, Object> data = new HashMap<>();
                data.put("success", true);
                result.put("data", data);
                System.out.println("✅ 添加处理记录成功，异常ID: " + alertIdLong + ", 状态: " + status);
            } else {
                result.put("code", 500);
                result.put("msg", "添加失败");
                Map<String, Object> data = new HashMap<>();
                data.put("success", false);
                result.put("data", data);
                System.out.println("❌ 添加处理记录失败");
            }

        } catch (NumberFormatException e) {
            result.put("code", 400);
            result.put("msg", "告警ID格式错误: " + alertId);
            result.put("data", null);
            System.out.println("❌ 告警ID格式错误: " + alertId);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "添加失败: " + e.getMessage());
            result.put("data", null);
            System.out.println("❌ 添加处理记录异常: " + e.getMessage());
        }

        return result;
    }


    /**
     * 获取相关设备数据
     */
    private List<Map<String, Object>> getRelatedDevices() {
        List<Map<String, Object>> devices = new ArrayList<>();

        try {
            // 从数据库获取设备信息
            List<DeviceInfo> deviceList = deviceInfoMapper.selectList(null);

            for (DeviceInfo device : deviceList) {
                Map<String, Object> deviceInfo = new HashMap<>();
                deviceInfo.put("deviceId", device.getDeviceId());
                deviceInfo.put("deviceCode", device.getDeviceCode());
                // 直接使用设备编码，不添加"监测点"前缀
                deviceInfo.put("name", device.getDeviceCode() != null ? device.getDeviceCode() : "未知设备");
                deviceInfo.put("location", device.getInstallLocation() != null ? device.getInstallLocation() : "未知位置");
                deviceInfo.put("status", getDeviceStatusText(device.getStatus()));
                deviceInfo.put("statusCode", device.getStatus());
                deviceInfo.put("icon", "location");
                devices.add(deviceInfo);
            }

            System.out.println("📱 获取到 " + devices.size() + " 个相关设备");

        } catch (Exception e) {
            System.err.println("❌ 获取相关设备失败: " + e.getMessage());
            e.printStackTrace();

            // 如果数据库查询失败，返回默认数据
            devices = getDefaultDevices();
        }

        return devices;
    }

    /**
     * 获取相关设备数据（包含当前告警设备）
     */
    private List<Map<String, Object>> getRelatedDevices(String alertDeviceId) {
        List<Map<String, Object>> devices = new ArrayList<>();

        try {
            // 首先添加当前告警的设备
            if (alertDeviceId != null && !alertDeviceId.isEmpty()) {
                QueryWrapper<DeviceInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("device_code", alertDeviceId);
                DeviceInfo alertDevice = deviceInfoMapper.selectOne(queryWrapper);
                if (alertDevice != null) {
                    Map<String, Object> alertDeviceInfo = new HashMap<>();
                    alertDeviceInfo.put("deviceId", alertDevice.getDeviceId());
                    alertDeviceInfo.put("deviceCode", alertDevice.getDeviceCode());
                    alertDeviceInfo.put("name", alertDevice.getDeviceCode() != null ? alertDevice.getDeviceCode() : "未知设备");
                    alertDeviceInfo.put("location", alertDevice.getInstallLocation() != null ? alertDevice.getInstallLocation() : "未知位置");
                    alertDeviceInfo.put("status", getDeviceStatusText(alertDevice.getStatus()));
                    alertDeviceInfo.put("statusCode", alertDevice.getStatus());
                    alertDeviceInfo.put("icon", "location");
                    alertDeviceInfo.put("isCurrentAlert", true); // 标记为当前告警设备
                    devices.add(alertDeviceInfo);
                    System.out.println("📱 添加当前告警设备: " + alertDevice.getDeviceCode());
                } else {
                    // 如果数据库中找不到设备，创建默认设备信息
                    Map<String, Object> defaultAlertDevice = new HashMap<>();
                    defaultAlertDevice.put("deviceId", 0L);
                    defaultAlertDevice.put("deviceCode", alertDeviceId);
                    defaultAlertDevice.put("name", alertDeviceId);
                    defaultAlertDevice.put("location", "河北省保定市莲池区");
                    defaultAlertDevice.put("status", "在线");
                    defaultAlertDevice.put("statusCode", 1);
                    defaultAlertDevice.put("icon", "location");
                    defaultAlertDevice.put("isCurrentAlert", true);
                    devices.add(defaultAlertDevice);
                    System.out.println("📱 添加默认告警设备: " + alertDeviceId);
                }
            }

            // 不再添加其他设备，只显示当前告警设备

            System.out.println("📱 获取到 " + devices.size() + " 个相关设备（包含当前告警设备）");

        } catch (Exception e) {
            System.err.println("❌ 获取相关设备失败: " + e.getMessage());
            e.printStackTrace();

            // 如果数据库查询失败，返回默认数据
            devices = getDefaultDevicesWithAlert(alertDeviceId);
        }

        return devices;
    }

    /**
     * 获取默认设备数据（当数据库查询失败时使用）
     */
    private List<Map<String, Object>> getDefaultDevices() {
        List<Map<String, Object>> devices = new ArrayList<>();

        Map<String, Object> device1 = new HashMap<>();
        device1.put("deviceId", 1L);
        device1.put("deviceCode", "ESP8266_001");
        device1.put("name", "ESP8266_001");
        device1.put("location", "河北省保定市莲池区");
        device1.put("status", "在线");
        device1.put("statusCode", 1);
        device1.put("icon", "location");
        devices.add(device1);


        return devices;
    }

    /**
     * 获取默认设备数据（包含当前告警设备）
     */
    private List<Map<String, Object>> getDefaultDevicesWithAlert(String alertDeviceId) {
        List<Map<String, Object>> devices = new ArrayList<>();

        // 首先添加当前告警设备
        if (alertDeviceId != null && !alertDeviceId.isEmpty()) {
            Map<String, Object> alertDevice = new HashMap<>();
            alertDevice.put("deviceId", 0L);
            alertDevice.put("deviceCode", alertDeviceId);
            alertDevice.put("name", alertDeviceId);
            alertDevice.put("location", "未知位置");
            alertDevice.put("status", "在线");
            alertDevice.put("statusCode", 1);
            alertDevice.put("icon", "location");
            alertDevice.put("isCurrentAlert", true);
            devices.add(alertDevice);
        }

        // 添加其他默认设备
        Map<String, Object> device1 = new HashMap<>();
        device1.put("deviceId", 1L);
        device1.put("deviceCode", "ESP8266_002");
        device1.put("name", "ESP8266_002");
        device1.put("location", "西湖区");
        device1.put("status", "离线");
        device1.put("statusCode", 2);
        device1.put("icon", "location");
        device1.put("isCurrentAlert", false);
        devices.add(device1);

        Map<String, Object> device2 = new HashMap<>();
        device2.put("deviceId", 2L);
        device2.put("deviceCode", "ESP8266_003");
        device2.put("name", "ESP8266_003");
        device2.put("location", "青山湖区");
        device2.put("status", "故障");
        device2.put("statusCode", 3);
        device2.put("icon", "location");
        device2.put("isCurrentAlert", false);
        devices.add(device2);

        return devices;
    }

    /**
     * 获取设备状态文本
     */
    private String getDeviceStatusText(Integer status) {
        if (status == null) return "未知";

        switch (status) {
            case 1:
                return "在线";
            case 2:
                return "离线";
            case 3:
                return "故障";
            default:
                return "未知";
        }
    }

    /**
     * 获取处理记录（从数据库查询）
     */
    private List<Map<String, Object>> getRealProcessRecords(Long anomalyId) {
        List<Map<String, Object>> records = new ArrayList<>();

        try {
            System.out.println("🔍 开始查询数据库处理记录，异常ID: " + anomalyId);

            // 查询数据库中的处理记录
            QueryWrapper<com.zhentao.pojo.WaterAnomalyLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("anomaly_id", anomalyId);
            queryWrapper.orderByAsc("create_time");

            List<com.zhentao.pojo.WaterAnomalyLog> logs = waterAnomalyLogMapper.selectList(queryWrapper);

            System.out.println("📊 数据库查询结果: " + logs.size() + " 条记录");

            if (logs.isEmpty()) {
                // 如果数据库中没有记录，返回空数组，不插入测试数据
                System.out.println("📋 数据库中没有处理记录，返回空数组");
                return records; // 返回空的records列表
            }

            // 转换数据库记录为前端需要的格式
            for (com.zhentao.pojo.WaterAnomalyLog log : logs) {
                Map<String, Object> record = new HashMap<>();
                record.put("type", getStatusType(log.getStatus()));
                record.put("title", getStatusTitle(log.getStatus()));
                record.put("description", getStatusDescription(log.getStatus()));
                record.put("time", log.getCreateTime()); // 使用数据库中的实际时间
                records.add(record);
            }

            System.out.println("✅ 成功处理 " + records.size() + " 条处理记录");

        } catch (Exception e) {
            System.err.println("❌ 查询数据库处理记录失败: " + e.getMessage());
            e.printStackTrace();
            // 如果查询失败，返回空数组
            records = new ArrayList<>();
        }

        return records;
    }

    /**
     * 插入测试处理记录到数据库
     */
    private void insertTestProcessRecords(Long anomalyId) {
        try {
            System.out.println("📝 开始插入测试处理记录到数据库，异常ID: " + anomalyId);

            // 获取告警创建时间作为基准
            Date alertCreateTime = getAlertCreateTime(anomalyId);
            if (alertCreateTime == null) {
                alertCreateTime = new Date();
            }

            // 插入告警创建记录
            com.zhentao.pojo.WaterAnomalyLog createLog = new com.zhentao.pojo.WaterAnomalyLog();
            createLog.setAnomalyId(anomalyId.intValue());
            createLog.setStatus(1);
            createLog.setCreateTime(alertCreateTime);
            waterAnomalyLogMapper.insert(createLog);

            // 插入分配处理记录
            com.zhentao.pojo.WaterAnomalyLog assignLog = new com.zhentao.pojo.WaterAnomalyLog();
            assignLog.setAnomalyId(anomalyId.intValue());
            assignLog.setStatus(2);
            assignLog.setCreateTime(new Date(alertCreateTime.getTime() + 5 * 60 * 1000)); // 5分钟后
            waterAnomalyLogMapper.insert(assignLog);

            // 插入确认告警记录
            com.zhentao.pojo.WaterAnomalyLog confirmLog = new com.zhentao.pojo.WaterAnomalyLog();
            confirmLog.setAnomalyId(anomalyId.intValue());
            confirmLog.setStatus(3);
            confirmLog.setCreateTime(new Date(alertCreateTime.getTime() + 15 * 60 * 1000)); // 15分钟后
            waterAnomalyLogMapper.insert(confirmLog);

            System.out.println("✅ 成功插入测试处理记录到数据库");

        } catch (Exception e) {
            System.err.println("❌ 插入测试处理记录失败: " + e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 根据状态获取类型
     */
    private String getStatusType(Integer status) {
        if (status == null) return "create";

        switch (status) {
            case 1:
                return "create";  // 创建警告 - 红色
            case 2:
                return "assign";  // 确定警告 - 黄橙色
            case 3:
                return "handle";  // 处理警告 - 绿色
            default:
                return "create";
        }
    }

    /**
     * 根据状态获取标题
     */
    private String getStatusTitle(Integer status) {
        if (status == null) return "告警创建";

        switch (status) {
            case 1:
                return "告警创建";
            case 2:
                return "确定告警";
            case 3:
                return "处理告警";
            default:
                return "告警创建";
        }
    }

    /**
     * 根据状态获取描述
     */
    private String getStatusDescription(Integer status) {
        if (status == null) return "系统监测到异常数据，自动创建警告";

        switch (status) {
            case 1:
                return "系统监测到异常数据，自动创建警告";
            case 2:
                return "警告已确定，正在去往现场";
            case 3:
                return "警告已解决";
            default:
                return "系统监测到异常数据，自动创建警告";
        }
    }

    /**
     * 生成默认的处理记录（基于告警创建时间）
     */
    private List<Map<String, Object>> generateDefaultProcessRecords(Long anomalyId) {
        List<Map<String, Object>> records = new ArrayList<>();

        try {
            // 先查询告警的创建时间
            Date alertCreateTime = getAlertCreateTime(anomalyId);
            if (alertCreateTime == null) {
                // 如果查询不到告警创建时间，使用当前时间
                alertCreateTime = new Date();
            }

            System.out.println("📅 告警创建时间: " + alertCreateTime);

        // 告警创建记录 - 使用告警的实际创建时间
        Map<String, Object> createRecord = new HashMap<>();
        createRecord.put("type", "create");
        createRecord.put("title", "告警创建");
        createRecord.put("description", "系统监测到异常数据，自动创建警告");
        createRecord.put("time", alertCreateTime);
        createRecord.put("createTime", alertCreateTime);
        records.add(createRecord);

            // 分配处理记录 - 告警创建后5分钟
            Map<String, Object> assignRecord = new HashMap<>();
            assignRecord.put("type", "assign");
            assignRecord.put("title", "分配处理");
            assignRecord.put("description", "警告已确定，正在去往现场");
            Date assignTime = new Date(alertCreateTime.getTime() + 5 * 60 * 1000); // 5分钟后
            assignRecord.put("time", assignTime);
            assignRecord.put("createTime", assignTime);
            records.add(assignRecord);

            // 确认告警记录 - 告警创建后15分钟
            Map<String, Object> confirmRecord = new HashMap<>();
            confirmRecord.put("type", "confirm");
            confirmRecord.put("title", "确认告警");
            confirmRecord.put("description", "警告已解决");
            Date confirmTime = new Date(alertCreateTime.getTime() + 15 * 60 * 1000); // 15分钟后
            confirmRecord.put("time", confirmTime);
            confirmRecord.put("createTime", confirmTime);
            records.add(confirmRecord);

            System.out.println("✅ 生成基于告警创建时间的处理记录，告警ID: " + anomalyId);

        } catch (Exception e) {
            System.err.println("❌ 生成处理记录失败: " + e.getMessage());
            e.printStackTrace();

            // 如果出错，使用当前时间作为基准
            Date currentTime = new Date();

            Map<String, Object> createRecord = new HashMap<>();
            createRecord.put("type", "create");
            createRecord.put("title", "告警创建");
            createRecord.put("description", "系统监测到异常数据，自动创建警告");
            Date createTime = new Date(currentTime.getTime() - 30 * 60 * 1000);
            createRecord.put("time", createTime);
            createRecord.put("createTime", createTime);
            records.add(createRecord);

            Map<String, Object> assignRecord = new HashMap<>();
            assignRecord.put("type", "assign");
            assignRecord.put("title", "分配处理");
            assignRecord.put("description", "警告已确定，正在去往现场");
            Date assignTime = new Date(currentTime.getTime() - 20 * 60 * 1000);
            assignRecord.put("time", assignTime);
            assignRecord.put("createTime", assignTime);
            records.add(assignRecord);

            Map<String, Object> confirmRecord = new HashMap<>();
            confirmRecord.put("type", "confirm");
            confirmRecord.put("title", "确认告警");
            confirmRecord.put("description", "警告已解决");
            Date confirmTime = new Date(currentTime.getTime() - 10 * 60 * 1000);
            confirmRecord.put("time", confirmTime);
            confirmRecord.put("createTime", confirmTime);
            records.add(confirmRecord);
        }

        return records;
    }

    /**
     * 获取告警创建时间
     */
    private Date getAlertCreateTime(Long anomalyId) {
        try {
            // 查询告警的创建时间
            QueryWrapper<WaterQualityAnomaly> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("anomaly_id", anomalyId);
            queryWrapper.select("create_time");

            WaterQualityAnomaly alert = waterQualityAnomalyMapper.selectOne(queryWrapper);
            if (alert != null && alert.getCreateTime() != null) {
                System.out.println("📅 查询到告警创建时间: " + alert.getCreateTime());
                return alert.getCreateTime();
            } else {
                System.out.println("⚠️ 未找到告警或创建时间为空，异常ID: " + anomalyId);
                return null;
            }
        } catch (Exception e) {
            System.err.println("❌ 查询告警创建时间失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

}
